package com.bucket.cloud.common.core.util;

import com.bucket.cloud.common.core.exception.BucketException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileUtil {

    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * NIO way
     */
    public static byte[] toByteArray(String filename) {

        File f = new File(filename);
        if (!f.exists()) {
            log.error("文件未找到！" + filename);
            throw new BucketException("文件未找到！");
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
                // do nothing
                // System.out.println("reading");
            }
            return byteBuffer.array();
        } catch (IOException e) {
            throw new BucketException("FILE_READING_ERROR!");
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                throw new BucketException("FILE_READING_ERROR!");
            }
            try {
                fs.close();
            } catch (IOException e) {
                throw new BucketException("FILE_READING_ERROR!");
            }
        }
    }

    /**
     * 删除目录
     *
     * @author cyq
     * @Date 2017/10/30 下午4:15
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * @Author: cyq
     * @Description:图片转化成base64字符串
     * @Date: 2018/7/12-15:26
     * @parm:
     */
    public static String GetImageStr(String url) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(url);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    /**
     * @Author: cyq
     * @Description: base64字符串转化成图片
     * @Date: 2018/7/12-15:27
     * @parm:
     */
    public static boolean GenerateImage(String imgStr, String fileSavePath) {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            OutputStream out = new FileOutputStream(fileSavePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            throw new BucketException("FILE_READING_ERROR!");
        }
    }

    /**
     * @Author: cyq
     * @Description: 计算base64的图片的大小
     * @Date: 2018/7/12-15:57
     * @parm:
     */
    public static Integer imageSize(String image) {
        String str = image.substring(22); // 1.需要计算文件流大小，首先把头部的data:image/png;base64,（注意有逗号）去掉。
        Integer equalIndex = str.indexOf("=");//2.找到等号，把等号也去掉
        if (str.indexOf("=") > 0) {
            str = str.substring(0, equalIndex);
        }
        Integer strLength = str.length();//3.原来的字符流大小，单位为字节
        Integer size = strLength - (strLength / 8) * 2;//4.计算后得到的文件流大小，单位为字节
        return size;
    }

    /**
     * @auther: cyq
     * @Description: 判断文件夹路径是否存在 不存在则创建
     * @Date: 2018/10/15 11:59
     * @param: [dirPath] 文件夹路径
     * @return: void
     */
    public static void judgeDirIsExist(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}